# coding: utf-8
from pathlib import Path

from PyFilesDownloader.Qt import M3u8DownloaderThread
from PySide6.QtCore import Qt, Signal
from PySide6.QtGui import QColor
from PySide6.QtWidgets import QHBoxLayout, QVBoxLayout
from qeventmanager import qevent_manager
from qfluentwidgets import SimpleCardWidget, IconWidget, FluentIcon, setFont, ProgressBar, MessageBoxBase, \
    SubtitleLabel, CheckBox

from common import cfg, openUrl
from common.server import VideoModel, BananaServer
from ..widgets import ImageLabel, BodyLabel, ToolTipButton, Alert


class DeleteTaskDialog(MessageBoxBase):

    def __init__(self, parent=None, showCheckBox=True, deleteOnClose=True):
        super().__init__(parent)
        self.titleLabel = SubtitleLabel('删除任务', self)
        self.contentLabel = BodyLabel('您确定要删除此任务吗?', self)
        self.deleteFileCheckBox = CheckBox('删除文件', self)

        self.deleteFileCheckBox.setVisible(showCheckBox)

        if deleteOnClose:
            self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose, True)

        self._initWidgets()

    def _initWidgets(self):
        self.deleteFileCheckBox.setChecked(True)
        self.widget.setMinimumWidth(330)

        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)
        layout.addWidget(self.titleLabel)
        layout.addSpacing(12)
        layout.addWidget(self.contentLabel)
        layout.addSpacing(10)
        layout.addWidget(self.deleteFileCheckBox)
        self.viewLayout.addLayout(layout)


class TaskCardBase(SimpleCardWidget):
    deleted = Signal(object)

    def __init__(self, parent=None):
        super().__init__(parent)
        self.localFile = None  # type: Path
        self.model = None  # type: VideoModel
        self.horizontalLayout = QHBoxLayout(self)
        self.verticalLayout = QVBoxLayout()
        self.horizontalLayout_2 = QHBoxLayout()

        self.coverLabel = ImageLabel(self)
        self.titleLabel = BodyLabel('Video Title', self)
        self.iconLabel = IconWidget(FluentIcon.DATE_TIME, self)
        self.logLabel = BodyLabel('2022-01-01 12:00:00', self)

        self.__initWidgets()

    def __initWidgets(self):
        self.setFixedHeight(100)
        self.coverLabel.setRadius(5)
        self.coverLabel.setFixedWidth(120)
        self.iconLabel.setFixedSize(14, 14)
        setFont(self.titleLabel, 20)
        setFont(self.logLabel, 12)
        self.logLabel.setTextColor(QColor(100, 100, 100), QColor(150, 150, 150))

        self.horizontalLayout.addWidget(self.coverLabel)
        self.horizontalLayout.addSpacing(15)
        self.verticalLayout.setAlignment(Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft)
        self.verticalLayout.addWidget(self.titleLabel)

        self.horizontalLayout_2.setAlignment(Qt.AlignmentFlag.AlignLeft)
        self.horizontalLayout_2.addWidget(self.iconLabel)
        self.horizontalLayout_2.addWidget(self.logLabel)

        self.verticalLayout.addLayout(self.horizontalLayout_2)
        self.horizontalLayout.addLayout(self.verticalLayout)
        self.horizontalLayout.addSpacing(15)

    def setTitle(self, title: str):
        self.titleLabel.setText(title)

    def title(self) -> str:
        return self.titleLabel.text()

    def setLog(self, log: str):
        self.logLabel.setText(log)

    def log(self) -> str:
        return self.logLabel.text()

    def setCoverUrl(self, url: str):
        self.coverLabel.setUrl(url)

    def _onDeleteButtonClicked(self):
        w = DeleteTaskDialog(self.window(), deleteOnClose=False)
        w.deleteFileCheckBox.setChecked(False)

        if w.exec():
            self.removeTask(w.deleteFileCheckBox.isChecked())
            self.deleted.emit(self)

        w.deleteLater()

    def removeTask(self, deleteFile=False):
        raise NotImplementedError

    def setLocalFile(self, file_path: str):
        self.localFile = Path(file_path)

    def _showLocalFile(self):
        if self.localFile is None:
            return
        openUrl(self.localFile.as_posix())

    def setModel(self, model: VideoModel):
        self.setTitle(model.title)
        self.setCoverUrl(model.cover_url)
        self.model = model
        self.setLocalFile(cfg.get(cfg.downloadFolder) + '/' + model.title + '.mp4')


class DownloadingTaskCard(TaskCardBase):
    statusChanged = Signal(bool)

    def __init__(self, parent=None):
        super().__init__(parent)
        self.progressBar = ProgressBar(self)
        self.startButton = ToolTipButton.toolButton(self, FluentIcon.PLAY, '开始/继续下载')
        self.openFolderButton = ToolTipButton.toolButton(self, FluentIcon.FOLDER, '打开文件夹')
        self.deleteButton = ToolTipButton.toolButton(self, FluentIcon.DELETE, '删除')

        self.downloadThread = M3u8DownloaderThread(self)

        self.__initWidgets()

    def __initWidgets(self):
        self.progressBar.setValue(50)
        self.verticalLayout.addWidget(self.progressBar)
        self.horizontalLayout.addWidget(self.startButton)
        self.horizontalLayout.addWidget(self.openFolderButton)
        self.horizontalLayout.addWidget(self.deleteButton)

        self.__connectSignals()

    def __connectSignals(self):
        self.downloadThread.progressSignal.connect(self.progressBar.setValue)
        self.downloadThread.logSignal.connect(self.logLabel.setText)
        self.downloadThread.started.connect(self._onStarted)
        self.downloadThread.finished.connect(self._onFinished)

        self.startButton.clicked.connect(self._onStartButtonClicked)
        self.openFolderButton.clicked.connect(self._showLocalFile)
        self.deleteButton.clicked.connect(self._onDeleteButtonClicked)

    def _onStarted(self):
        self.startButton.setIcon(FluentIcon.PAUSE)
        self.startButton.setToolTip('暂停下载')
        self.startButton.setEnabled(True)
        self.statusChanged.emit(True)

    def _onFinished(self):
        self.startButton.setIcon(FluentIcon.PLAY)
        self.startButton.setToolTip('开始/继续下载')
        self.startButton.setEnabled(True)
        self.statusChanged.emit(False)

    def _onStartButtonClicked(self):
        if self.isRunning():
            self.downloadThread.stop()
        else:
            self.downloadThread.start()

    def start(self):
        file_name = self.titleLabel.text() + '.mp4'
        save_path = Path(cfg.get(cfg.downloadFolder))
        if (save_path / file_name).exists():
            self.progressBar.setValue(100)
            self.logLabel.setText('文件已存在')
            return
        self.startButton.setEnabled(False)
        self.downloadThread.start()

    def isRunning(self):
        return self.downloadThread.isRunning()

    def stop(self):
        if self.isRunning():
            self.downloadThread.stop()

    def setParams(self, m3u8_url: str):
        file_name = self.titleLabel.text() + '.mp4'
        save_path = Path(cfg.get(cfg.downloadFolder))

        self.downloadThread.setParams(
            url=m3u8_url,
            save_path=save_path,
            file_name=file_name,
            semaphore=8
        )
        self.start()

    def setModel(self, model: VideoModel):
        super().setModel(model)
        m3u8_url = model.m3u8_url
        if m3u8_url:
            self.setParams(m3u8_url)
        elif model.vod_id:
            qevent_manager.addTaskToPool(BananaServer.replay, model.vod_id, isMin=model.is_mini, slot=self.setParams)

    def isSuccess(self):
        file_name = self.titleLabel.text() + '.mp4'
        save_path = Path(cfg.get(cfg.downloadFolder))
        return (save_path / file_name).exists()


class SuccessTaskCard(TaskCardBase):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.playButton = ToolTipButton.toolButton(self, FluentIcon.PLAY, '本地播放')
        self.openFolderButton = ToolTipButton.toolButton(self, FluentIcon.FOLDER, '打开文件夹')
        self.deleteButton = ToolTipButton.toolButton(self, FluentIcon.DELETE, '删除')

        self.logLabel.setVisible(False)
        self.iconLabel.setVisible(False)

        self.horizontalLayout.addWidget(self.playButton)
        self.horizontalLayout.addWidget(self.openFolderButton)
        self.horizontalLayout.addWidget(self.deleteButton)

        self.playButton.clicked.connect(self._onPlayButtonClicked)
        self.openFolderButton.clicked.connect(lambda: openUrl(self.localFile.parent))
        self.deleteButton.clicked.connect(self._onDeleteButtonClicked)

    def _onPlayButtonClicked(self):
        if openUrl(self.localFile.as_posix()) is False:
            Alert.warning('无法打开文件, 请检查文件是否损坏')
